package com.oa.kq.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.SequenceService;
import com.mdp.core.utils.BaseUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.kq.entity.Schedule;
import com.oa.kq.service.ScheduleService;
import com.oa.utils.ExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Controller
@RequestMapping(value = "/*/oa/kq/schedule")
@Api(tags = {"排班时间表-操作接口"})
public class ScheduleController {

    static Logger logger = LoggerFactory.getLogger(ScheduleController.class);

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private SequenceService seqService;

    /**
     * 新增一条数据
     *
     * @updateContent 返回类型改变 新增tips的返回参数
     * @update 2020/1/6 16:33
     * @updateAuthore LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/insertSchedule", method = RequestMethod.POST)
    public Result insertSchedule(@RequestBody Schedule schedule) {
        if (StringUtils.isEmpty(schedule.getId())) {
            schedule.setId(scheduleService.createKey("id"));
        } else {
            Schedule scheduleQuery = new Schedule();
            scheduleQuery.setId(schedule.getId());
            if (scheduleService.countByWhere(scheduleQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        if (schedule.getIsNeedatt() == null) {
            schedule.setIsNeedatt("0");
        }
        if (schedule.getNoonBreakBegin().equals("00:00")) {
            schedule.setNoonBreakBegin(null);
            schedule.setNoonBreakEnd(null);
        }
        if (!schedule.getScheduleType().equals("1")) {
            schedule.setNoonBreakBegin(null);
            schedule.setNoonBreakEnd(null);
        }
        scheduleService.insert(schedule);
        return Result.ok().setData(schedule);
    }

    /**
     * 删除班次
     */
    @ResponseBody
    @RequestMapping(value = "/deleteSchedule")
    public int deleteSchedule(String schId) {
        Schedule schedule = new Schedule();
        schedule.setId(schId);
        return scheduleService.deleteByPk(schedule);
    }


    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result del(@RequestBody Schedule acctCurrency) {
        scheduleService.deleteByPk(acctCurrency);
        return Result.ok("成功删除一条数据");
    }

    /**
     * 获取所有全局班次
     */
    @ResponseBody
    @RequestMapping(value = "/getAllSchedule")
    public List<Schedule> getAllSchedule() {
//        return scheduleService.getAllSchedule();
        Map<String, Object> params = new HashMap<>();
        IPage page = QueryTools.initPage(params);
        QueryWrapper qw = QueryTools.initQueryWrapper(Schedule.class, params);
        return scheduleService.selectListMapByWhere(page, qw, params).stream()
                .map((value) -> BaseUtils.fromMap(value, Schedule.class)).collect(Collectors.toList());
    }


    /**
     * 查询某个班次
     */
    @ResponseBody
    @RequestMapping(value = "/getScheduleInfo")
    public Schedule getScheduleInfo(String scheduleId) {
        Schedule schedule = new Schedule();
        schedule.setId(scheduleId);
        return scheduleService.selectOneObject(schedule);
    }

    /**
     * 修改班次信息
     */
    @ResponseBody
    @RequestMapping(value = "/updateSchedule")
    public Schedule updateSchedule(@ModelAttribute("schedule") Schedule schedule, BindingResult result, Model model) {
//        return scheduleService.updateSchedule(schedule);
        if (scheduleService.updateById(schedule)) {
            return schedule;
        }
        return null;
    }


    /**
     * 跳转到查询页面listSchedule.jsp
     * 修改逻辑 不需要返回jsp 直接返回数据
     *
     * @update 2020/1/6 16:59
     * @alterAuthor LinYuKun
     */
    @ResponseBody
    @RequestMapping(value = "/listSchedule", method = RequestMethod.GET)
    public Result listScheduleOld(@RequestParam Map<String, Object> params) {
        IPage page = QueryTools.initPage(params);
        QueryWrapper<Schedule> qw = QueryTools.initQueryWrapper(Schedule.class, params);
        List<Map<String, Object>> acctCurrencyList = scheduleService.selectListMapByWhere(page, qw, params);    //列出AcctCurrency列表
        return Result.ok("查询成功").setData(acctCurrencyList);
    }

    /**
     * 跳转到新增页面addSchedule.jsp
     */
    @RequestMapping(value = "/addSchedule")
    public ModelAndView addSchedule() {

        ModelAndView mv = new ModelAndView();
        Schedule schedule = new Schedule();
        mv.addObject("data", schedule);
        return mv;
    }

    /**
     * 请求需带json后缀,如selectListScheduleByPage.json
     * 根据条件查询数据对象列表
     */
    @RequestMapping(value = "/selectListScheduleByPage")
    public ModelAndView selectListScheduleByPage(@ModelAttribute("schedule") Schedule schedule, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();

//        List<Schedule> scheduleList = scheduleService.selectListByPage(schedule);    //列出Schedule列表
        List<Schedule> scheduleList = scheduleService.selectListByWhere(schedule);
        mv.addObject("data", scheduleList);
        Tips tips = new Tips("查询成功");
        mv.addObject("tips", tips);
        return mv;
    }


    /**
     * 根据主键修改一条数据
     */
    @RequestMapping(value = "/updateScheduleByPk")
    public ModelAndView updateScheduleByPk(@ModelAttribute("schedule") Schedule schedule, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功更新一条数据");
        scheduleService.updateByPk(schedule);
        mv.addObject("data", schedule);
        mv.addObject("tips", tips);
        return mv;
    }


    /**
     * 批量删除
     */
    @RequestMapping(value = "/batchDeleteSchedule")
    public ModelAndView batchDeleteSchedule(@RequestParam("id[]") String[] id) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功删除" + id.length + "条数据");
        List<Schedule> list = new ArrayList<Schedule>();
        for (int i = 0; i < id.length; i++) {
            Schedule schedule = new Schedule();
            schedule.setId(id[i]);
            list.add(schedule);
        }
        scheduleService.batchDelete(list);
        mv.addObject("tips", tips);
        return mv;
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value = "/exportScheduleToExcel")
    public ModelAndView exportScheduleToExcel(@ModelAttribute("schedule") Schedule schedule, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功导出数据");
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("编号id");
            titles.add("班次名称（用户自定义）");
            titles.add("上班时间09:30");
            titles.add("下班时间。");
            titles.add("上班弹性时间（分钟）");
            titles.add("严重迟到时间（分钟）");
            titles.add("部门id（）");
            titles.add("上班时间");
            titles.add("下班时间。");
            titles.add("上班时间");
            titles.add("下班时间。");
            titles.add("排班方式（0一天一次，1一天两次，2一天三次）");
            titles.add("下班是否需要打卡（0不需要，1需要）");
            titles.add("旷工时间（分钟）");
            titles.add("午休开始时间。一天一次班才有的");
            titles.add("午休结束时间");
            dataMap.put("titles", titles);
            List<Schedule> ScheduleList = scheduleService.selectListByWhere(schedule);
            List<Map<String, Object>> allList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < ScheduleList.size(); i++) {
                Map<String, Object> row = new HashMap<String, Object>();
                row.put("var1", ScheduleList.get(i).getId());
                row.put("var2", ScheduleList.get(i).getScheduleName());
                row.put("var3", ScheduleList.get(i).getWorkTimea());
                row.put("var4", ScheduleList.get(i).getReleaseTimea());
                row.put("var5", ScheduleList.get(i).getFlexibleTime());
                row.put("var6", ScheduleList.get(i).getLateTime());
                row.put("var7", ScheduleList.get(i).getDeptid());
                row.put("var8", ScheduleList.get(i).getWorkTimeb());
                row.put("var9", ScheduleList.get(i).getReleaseTimeb());
                row.put("var10", ScheduleList.get(i).getWorkTimec());
                row.put("var11", ScheduleList.get(i).getReleaseTimec());
                row.put("var12", ScheduleList.get(i).getScheduleType());
                row.put("var13", ScheduleList.get(i).getIsNeedatt());
                row.put("var14", ScheduleList.get(i).getAbsenteeismTime());
                row.put("var15", ScheduleList.get(i).getNoonBreakBegin());
                row.put("var16", ScheduleList.get(i).getNoonBreakEnd());
                allList.add(row);
            }
            dataMap.put("varList", allList);
            ExcelView erv = new ExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            tips.setErrMsg("导出数据异常");
        }
        mv.addObject("tips", tips);
        return mv;
    }


    @ResponseBody
    @ApiOperation(value = "排班时间表-查询列表", notes = " ")
    @ApiEntityParams(Schedule.class)
    @ApiResponses({@ApiResponse(code = 200, response = Schedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listSchedule(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<Schedule> qw = QueryTools.initQueryWrapper(Schedule.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = scheduleService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ResponseBody
    @ApiOperation(value = "排班时间表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Schedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addSchedule(@RequestBody Schedule schedule) {
        scheduleService.save(schedule);
        return Result.ok("add-ok", "添加成功！");
    }

    @ResponseBody
    @ApiOperation(value = "排班时间表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delSchedule(@RequestBody Schedule schedule) {
        scheduleService.removeById(schedule);
        return Result.ok("del-ok", "删除成功！");
    }

    @ResponseBody
    @ApiOperation(value = "排班时间表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Schedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editSchedule(@RequestBody Schedule schedule) {
        scheduleService.updateById(schedule);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ResponseBody
    @ApiOperation(value = "排班时间表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = Schedule.class, props = {}, remark = "排班时间表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = Schedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        scheduleService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ResponseBody
    @ApiOperation(value = "排班时间表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelSchedule(@RequestBody List<Schedule> schedules) {
        User user = LoginUtils.getCurrentUserInfo();
        if (schedules.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<Schedule> datasDb = scheduleService.listByIds(schedules.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<Schedule> can = new ArrayList<>();
        List<Schedule> no = new ArrayList<>();
        for (Schedule data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            scheduleService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ResponseBody
    @ApiOperation(value = "排班时间表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Schedule.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(Schedule schedule) {
        Schedule data = (Schedule) scheduleService.getById(schedule);
        return Result.ok().setData(data);
    }

}
